#!/usr/bin/python
# -*- coding:utf-8 -*-
#
# HappyPlane
#
# Created by meiguizhinian on 2019/1/2
# Copyright © 2019 lixiaolong. All rights reserved.

import os
import sys
from xml.dom.minidom import parse


class Asset:

	def __init__(self, root, filename):
		self.root = root
		self.path = str(os.path.join(root, filename))
		self.dom = parse(self.path)
		pass

	def clear(self):
		for node in self.dom.childNodes[0].childNodes:
			node.parentNode.removeChild(node)
			pass
		doc = self.dom.documentElement
		for node in doc.getElementsByTagName('qresource'):
			doc.removeChild(node)
			pass
		pass

	def save(self):
		with open(self.path, 'w') as f:
			f.write(self.dom.childNodes[0].toprettyxml(indent="    ")) # ignore xml tag
			f.close()
			pass
		pass

	def add(self, folder_name):
		folder_path = str(os.path.join(self.root, folder_name))
		self._add_resource(folder_name, "")

		filenames = os.listdir(folder_path)
		for filename in filenames:
			if filename.startswith("."):
				continue
			if not os.path.isdir(os.path.join(folder_path, filename)):
				continue
			self._add_resource(folder_name, filename)
			pass
		pass

	def _add_resource(self, folder_name, name):
		folder_path = str(os.path.join(self.root, folder_name))

		node = self.dom.createElement('qresource')
		node.setAttribute("prefix", "/" + name)
		self.dom.documentElement.appendChild(node)

		if len(name) == 0:
			filenames = os.listdir(folder_path)
			for filename in filenames:
				if filename.startswith("."):
					continue
				if os.path.isdir(os.path.join(folder_path, filename)):
					continue
				alias = filename
				text = os.path.join(folder_name, filename)
				child = self.dom.createElement('file')
				child.setAttribute("alias", alias)
				child.appendChild(self.dom.createTextNode(text))
				self.dom.documentElement.appendChild(child)
				node.appendChild(child)
				pass
		else:
			for path, dirs, files in os.walk(str(os.path.join(folder_path, name))):
				for file in sorted(files):
					if file.startswith("."):
						continue
					alias = str(os.path.join(path.replace(os.path.join(folder_path, name), "", 1), file))
					if alias.startswith("/"):
						alias = alias.replace("/", "", 1)
						pass
					text = str(os.path.join(path.replace(self.root + "/", ""), file))
					child = self.dom.createElement('file')
					child.setAttribute("alias", alias)
					child.appendChild(self.dom.createTextNode(text))
					node.appendChild(child)
					pass
				pass
			pass
		pass

	pass


if __name__ == '__main__':
	asset = Asset(os.getcwd(), "assets.qrc")
	asset.clear()
	asset.add("assets")
	asset.save()
	pass
